package com.iamnh.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.iamnh.dao.BaseDao;

public class BaseHibernateDao<T, PK extends java.io.Serializable> implements BaseDao<T, PK> {
	// 日志输出类

	protected static final Logger LOGGER = LoggerFactory.getLogger(BaseHibernateDao.class);

	// 泛型反射类

	private Class<T> entityClass;
	
	// 通过反射获取子类确定的泛型类

	@SuppressWarnings({ "rawtypes", "unchecked" })

	public BaseHibernateDao() {

		Type genType = getClass().getGenericSuperclass();

		Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

		entityClass = (Class) params[0];

	}

	/**
	 * 注入sessionFactory
	 */
	@Autowired
	@Qualifier("sessionFactory")
	private SessionFactory sessionFactory;

	public Session getSession() {

		// 事务必须是开启的(Required)，否则获取不到

		return sessionFactory.getCurrentSession();
	}

	@Override
	public T save(T entity) {
		this.getSession().save(entity);
		return entity;
	}

	@Override
	public T delete(T entity) {
		return null;
	}

	@Override
	public void update(T entity) {

	}

	@Override
	public T load(PK id) {
		return (T) getSession().load(this.entityClass, id);
	}

	@Override
	public T get(PK id) {
		return (T) getSession().get(this.entityClass, id);
	}

	@Override
	public int count() {
		return 0;
	}

	@Override
	public List<T> list() {
		return null;
	}

	@Override
	public void flush() {

	}

	@Override
	public void clear() {

	}

	@Override
	public T selectForUpdate(PK id) {
		return (T) getSession().get(this.entityClass, id,LockMode.WRITE);
	}

}
